package com.nuanshui.heatedloan.msgcenter.apppush.filter;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.middleware.msgcenter.bean.Model;
import com.nuanshui.heatedloan.msgcenter.apppush.annotation.AppPushFilterProvider;
import com.nuanshui.heatedloan.msgcenter.apppush.bean.AppPushResult;
import com.nuanshui.heatedloan.msgcenter.apppush.bean.Invoker;
import com.nuanshui.heatedloan.msgcenter.apppush.constant.AppPushResultStatus;
import com.nuanshui.heatedloan.msgcenter.model.AppPushMessage;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;

/**
 * 获取推送用户的 token 
 * @param 
 * @author guohao
 * @date 2017年1月12日 下午4:11:02
 * @since $
 */
@AppPushFilterProvider(value="pushTokenFilter",order=100)
public class PushTokenFilter implements  AppPushFilter  {

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserTokenService userTokenService;

	private Logger logger = LoggerFactory.getLogger(PushTokenFilter.class);
	
	@Override
	public AppPushResult invoke(Invoker invoker,AppPushMessage appPushMessage) {			
		List<String> userIds = appPushMessage.getMsgBody().getDstUserIds();
		if(userIds == null || userIds.isEmpty()) {//没有推送的用户，不再继续往下进行
		   AppPushResult appPushResult = new AppPushResult(AppPushResultStatus.USER_EMPTY);
		   return appPushResult;
		}
		
		String msgTypeName = null;
    	if(appPushMessage.getMsgBody().getMsgTypeName()!= null){
        	msgTypeName = appPushMessage.getMsgBody().getMsgTypeName();
    	}
		List<HashMap<String,Object>> maps = selectUserTokensByUserIds(userIds,appPushMessage.getMsgBody().getBizUserId(),msgTypeName,(String)appPushMessage.getMsgBody().getParams().get(Model.CLIENT_TYPE));
    
		if(maps.isEmpty()) {
			logger.error("获取不到 token, 无法推送!");
			AppPushResult appPushResult = new AppPushResult(AppPushResultStatus.USER_PUSH_TOKEN_EMPTY);
			return appPushResult;
		}
		appPushMessage.setUserTokens(maps);
	    return invoker.doInvoker(appPushMessage);
	}
	
	private List<HashMap<String, Object>> selectUserTokensByUserIds(List<String> userIds,String userId,String type,String clientType) {
		if(userIds.isEmpty()){
			userIds = null;
		}
		String  currentId = null;
		if(userId != null){
			currentId = IdTypeHandler.decode(userId)+"";
		}
		return userTokenService.selectUserTokensByUserIds(userIds,currentId,type,clientType);
	}

}
